import React from 'react';
import { Layout, Menu } from 'antd';
// import menus from "../../router/menu";
import style from '../Layout.module.less';
import { useHistory } from 'react-router-dom';
import { routeItem } from '@/router';
import { useSelector, useDispatch } from 'react-redux';
import { changeTabList, replaceActiveKey } from '@/store/counterSlice';
import { getSingArray } from '@/utils/gloabl';
import { useTranslation } from 'react-i18next';

const { Sider } = Layout;
const { SubMenu } = Menu;
const BaseMenu = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const { collapsed, tabList, activeKey, menus } = useSelector((state: any) => ({
    collapsed: state.counter.collapsed,
    tabList: state.counter.tabList,
    activeKey: state.counter.activeKey,
    menus: state.counter.menus,
  }));
  const history = useHistory();
  const handleClick = (item: routeItem) => {
    dispatch(replaceActiveKey({ activeKey: item.path }));
    history.push(item.path);
    const arr = JSON.parse(JSON.stringify(tabList));
    arr.push({ title: item.title, path: item.path, name: item.name });
    dispatch(changeTabList({ tabList: getSingArray(arr, 'path') }));
    localStorage.setItem('tabList', JSON.stringify(getSingArray(arr, 'path')));
  };
  return (
    <Sider trigger={null} collapsible collapsed={collapsed} className={style.sider}>
      <Menu theme="dark" mode="inline" selectedKeys={[activeKey]}>
        {menus.map((item: routeItem) => {
          if (item.children) {
            return (
              <SubMenu
                key={item.path}
                title={t(item.name as string)}
                icon={<i className={`iconfont ${item.icon}`} />}
              >
                {item.children.map((m) => {
                  return (
                    <Menu.Item
                      key={m.path}
                      onClick={() => {
                        handleClick(m);
                      }}
                    >
                      {t(m.name as string)}
                    </Menu.Item>
                  );
                })}
              </SubMenu>
            );
          } else {
            return (
              <Menu.Item
                key={item.path}
                icon={<i className={`iconfont ${item.icon}`} />}
                onClick={() => {
                  handleClick(item);
                }}
              >
                {t(item.name as string)}
              </Menu.Item>
            );
          }
        })}
      </Menu>
    </Sider>
  );
};

export default BaseMenu;
